package com.atguigu.chapter11;

import com.atguigu.chapter05.WaterSensor;
import org.apache.flink.api.common.eventtime.WatermarkStrategy;
import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.table.api.DataTypes;
import org.apache.flink.table.api.Table;
import org.apache.flink.table.api.bridge.java.StreamTableEnvironment;
import org.apache.flink.table.descriptors.Csv;
import org.apache.flink.table.descriptors.FileSystem;
import org.apache.flink.table.descriptors.Schema;
import org.apache.flink.types.Row;

import java.time.Duration;

import static org.apache.flink.table.api.Expressions.$;

/**
 * TODO
 *
 * @author cjp
 * @version 1.0
 * @date 2021/3/12 9:30
 */
public class Flink05_TableAPI_Connector_FileSink {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);


        SingleOutputStreamOperator<WaterSensor> sensorDS = env
                .socketTextStream("localhost", 9999)
//                .readTextFile("input/sensor.csv")
                .map(new MapFunction<String, WaterSensor>() {
                    @Override
                    public WaterSensor map(String value) throws Exception {
                        // 切分
                        String[] line = value.split(",");
                        return new WaterSensor(line[0], Long.parseLong(line[1]), Integer.parseInt(line[2]));

                    }
                })
                .assignTimestampsAndWatermarks(
                        WatermarkStrategy
                                .<WaterSensor>forBoundedOutOfOrderness(Duration.ofSeconds(3))
                                .withTimestampAssigner((value, ts) -> value.getTs() * 1000L)
                );

        // TODO - Connector外部系统，写 文件
        StreamTableEnvironment tableEnv = StreamTableEnvironment.create(env);

        Table inputTable = tableEnv.fromDataStream(sensorDS);

        tableEnv
                .connect(new FileSystem().path("out/flinksql-sink.txt")
                )
                .withFormat(new Csv().fieldDelimiter('|'))
                .withSchema(new Schema()
                        .field("a", DataTypes.STRING())
                        .field("b", DataTypes.BIGINT())
                        .field("c", DataTypes.INT())
                )
                .createTemporaryTable("fileTable");


        Table resultTable = inputTable
                .where($("vc").isGreaterOrEqual(3))
                .select($("*"));

        // 将 Table 直接 写入 外部系统
        resultTable.executeInsert("fileTable");


        env.execute();
    }
}

/**
 * 通过 connector 将外部系统抽象成 动态表
 * 1、表环境.connect(外部系统描述器，指定相关参数)
 * 2、指定数据的存储格式
 * 3、指定 表结构
 * 4、指定 临时表的名字
 */
